<script setup lang="tsx">
import BaseInfo from './components/Detail/BaseInfo/index.vue'
import Panorama from './components/Detail/Panorama/index.vue'
import Team from './components/Detail/Team/index.vue'
import Journey from './components/Detail/Journey/index.vue'
import ContractOrder from './components/Detail/ContractOrder/index.vue'
import WorkOrderRecord from './components/Detail/WorkOrderRecord/index.vue'
import ReceiptManagement from './components/Detail/ReceiptManagement/index.vue'
import InvoicingHistory from './components/Detail/InvoicingHistory/index.vue'
import InvoicingInfo from './components/Detail/InvoicingInfo/index.vue'
import ReturnsRefund from './components/Detail/ReturnsRefund/index.vue'
import FileCabinet from './components/Detail/FileCabinet/index.vue'
import ApprovalRecord from './components/Detail/ApprovalRecord/index.vue'
import Marketplace from './components/Detail/Marketplace/index.vue'
import FollowList from './components/Detail/FollowList/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { getDetApi, returnPublicApi, getFieldEnumApi, updateRoleApi } from '@/api/customer'
import { CurdData, FieldEnum } from '@/api/customer/types'
import { SelectOption } from '@/api/global/types'
import { ElMessage } from 'element-plus'
import { useEnumeratePicker } from '@/utils'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { ElMessageBox } from 'element-plus'

const { push, go } = useRouter()

const { query } = useRoute()
const route = useRoute()
const { t } = useI18n()

// 通用选项生成函数
const createOptions = (enumObject: { [key: string]: string }) => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}

const isLoading = ref(true) // 设置加载状态
const currentRow = ref<Nullable<CurdData>>(null)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const stageOption = ref<Option[]>([])
const cusnatureOption = ref<Option[]>([])
let customerFieldEnum: FieldEnum = {}
interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}
let operatorOptions: SelectOption[] = []
const statusOption = ref<Option[]>([]) // 明确指定类型 Option[]
// 根据枚举值生成选项
const loadOptions = () => {
  statusOption.value = createOptions(customerFieldEnum?.status || {})
  stageOption.value = createOptions(customerFieldEnum?.stage || {})
  cusnatureOption.value = createOptions(customerFieldEnum?.cusnature || {})
}

const getCustomeDet = async () => {
  try {
    tableLoading.value = true
    const res = (await getDetApi(query.id as string)) as any
    currentRow.value = res.data

    // 清空之前添加的角色相关选项，只保留基础选项
    const baseOptions = [
      { label: '新建发票', value: 'newInvoice' },
      { label: '新建普通订单', value: 'newOrder' }
    ]
    options.splice(0, options.length, ...baseOptions)

    // 根据用户角色添加对应选项
    if (res.data.role === 'distributor') {
      options.push({ label: '设为普通用户', value: 'setNormalUser' })
    } else {
      options.push({ label: '设为经销商', value: 'setDistributor' })
    }

    // 更新过滤后的选项
    filteredOptions.value = [...options]

    dataList.value = res.data.items || []
    tableLoading.value = false
  } catch (e) {
    tableLoading.value = false
  }
}

const fetchData = async () => {
  await getCustomeDet()
  await getFieldEnumApi({ field: 'all' }).then((res) => {
    customerFieldEnum = res.data
  })
  await getOperatorSelectListApi({}).then((res) => {
    operatorOptions = res.data.list
  })
  isLoading.value = false // 数据加载完成后更新状态
  loadOptions()
}

const handleClick = (tab: any, event: Event) => {
  console.log(tab, event)
}

// 返回公海
const returnPublic = async (row: CurdData | null) => {
  ElMessageBox.confirm(
    t('confirmMessage.customer.returnPublicMessage'),
    t('confirmMessage.warning'),
    {
      confirmButtonText: t('confirmMessage.ok'),
      cancelButtonText: t('confirmMessage.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    const res = await returnPublicApi({
      id: row?.id
    })
    if (res) {
      ElMessage.success(t('confirmMessage.customer.returnPublicSuccess'))
    }
  })
}
// 跳转编辑
const action = (row, type: string) => {
  push(`/customer/customerList/${type}?id=${row.id}&source=/customerList/detail?id=${row.id}`)
}
const goup = (id) => {
  push(`/customer/customerList/detail?id=${409}`)
}
const godown = (id) => {
  push(`/customer/customerList/detail?id=${id}`)
}
//返回
const back = () => {
  push('/customer/customerList')
}

// const activeName = ref(decodeURIComponent(query.source as string) || 'base_info')
const activeName = ref('base_info')
// 根据 activeName 动态选择渲染的组件
const currentTabComponent = computed(() => {
  switch (activeName.value) {
    case 'base_info':
      return BaseInfo // 需要先定义 BaseInfo 组件
    case 'panorama':
      return Panorama // 需要先定义 Panorama 组件
    case 'team':
      return Team // 需要先定义 Team 组件
    case 'journey':
      return Journey // 需要先定义 Journey 组件
    case 'contract_order':
      return ContractOrder // 需要先定义 ContractOrder 组件
    case 'work_order_record':
      return WorkOrderRecord // 需要先定义 WorkOrderRecord 组件
    case 'receipt_management':
      return ReceiptManagement // 需要先定义 ReceiptManagement 组件
    case 'invoicing_history':
      return InvoicingHistory // 需要先定义 InvoicingHistory 组件
    case 'invoicing_info':
      return InvoicingInfo // 需要先定义 InvoicingInfo 组件
    case 'returns_refund':
      return ReturnsRefund // 需要先定义 ReturnsRefund 组件
    case 'file_cabinet':
      return FileCabinet // 需要先定义 FileCabinet 组件
    case 'approval_record':
      return ApprovalRecord // 需要先定义 ApprovalRecord 组件
    case 'marketplace':
      return Marketplace // 需要先定义 Marketplace 组件
    case 'follow_list':
      return FollowList // 需要先定义 FollowList 组件
    default:
      return '' // 默认渲染 BaseInfo 组件
  }
})
// 定义选项
const options = [{ label: '新建发票', value: 'newInvoice' }]

// 搜索文本
const searchText = ref('')

// 过滤后的选项
const filteredOptions = ref([...options])

// 过滤方法
const filterOptions = () => {
  filteredOptions.value = options.filter((item) => item.label.includes(searchText.value))
}

// 处理下拉菜单的操作
const handleCommand = (command) => {
  console.log('执行的操作：', command)
  switch (command) {
    case 'newContract':
      push('/contract/contractList/add')
      break
    case 'newInvoice':
      push(
        '/order/invoice-management/add?customer_id=' +
          currentRow?.value?.id +
          '&cusname=' +
          currentRow?.value?.cusname +
          '&source=' +
          `${'/customer/customerList/detail?id=' + currentRow?.value?.id}`
      )
      break
    case 'newOrder':
      push(
        `/order/order-management/add?customer_id=${currentRow?.value?.id}&cusname=${currentRow?.value?.cusname}`
      )
      break
    case 'newOpportunity':
      push('/opportunity/opportunityList/add')
      break
    case 'newUnpaidInvoice':
      push('/invoice/invoiceList/add')
      break
    case 'setFollowReminder':
      push('/customer/customerList/add')
      break
    case 'newFollowLog':
      push('/customer/customerList/add')
      break
    case 'setNormalUser':
      // 设为普通用户的逻辑
      handleRoleChange('user')
      break
    case 'setDistributor':
      // 设为经销商的逻辑
      handleRoleChange('distributor')
      break
  }
}

const handleRoleChange = async (role: string) => {
  ElMessageBox.confirm(
    '是否确认设为' + (role === 'user' ? '普通用户' : '经销商') + '？',
    t('confirmMessage.warning'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await updateRoleApi({ id: currentRow.value?.id, role })
    if (res) {
      ElMessage.success(t('common.operateSucMsg'))
      fetchData()
    }
  })
}

// 点击“新建联系人”按钮的操作
const handleCreateContact = () => {
  push('/customer/customerList/add')
}

onMounted(() => {
  console.log('66666666666')
  fetchData()
})
</script>

<template>
  <ContentDetailWrap :title="t('customer.detail')" @back="push('/customer/customerList')">
    <template #header v-if="!isLoading">
      <div class="header flex justify-between items-center">
        <div class="header-left flex flex-start items-center">
          <div class="right"
            ><div class="top">
              <p :style="{ fontWeight: 'bold', color: 'black' }"> {{ currentRow?.cusname }} </p>
            </div>
            <div class="bottom">
              <el-tag type="success" size="small" v-if="currentRow?.status">
                {{ useEnumeratePicker(statusOption, currentRow?.status ?? '') }}
              </el-tag>
              <el-tag type="warning" size="small" v-if="currentRow?.stage">
                {{ useEnumeratePicker(stageOption, currentRow?.stage ?? '') }}
              </el-tag>
              <el-tag type="primary" size="small" v-if="currentRow?.cusnature">
                {{ useEnumeratePicker(cusnatureOption, currentRow?.cusnature ?? '') }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="header-right">
          <!-- 主要按钮区 -->
          <div class="button-group">
            <el-button type="primary" class="main-button" @click="handleCreateContact">
              新建客户
            </el-button>

            <el-dropdown @command="handleCommand">
              <template #dropdown>
                <el-dropdown-menu>
                  <div class="dropdown-search">
                    <el-input
                      v-model="searchText"
                      placeholder="请输入搜索内容"
                      size="small"
                      clearable
                      @input="filterOptions"
                    >
                      <template #prefix>
                        <i class="el-icon-search"></i>
                      </template>
                    </el-input>
                  </div>
                  <el-dropdown-item
                    v-for="item in filteredOptions"
                    :key="item.value"
                    :command="item.value"
                  >
                    {{ item.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
              <el-button type="primary" class="triangle-button">
                <el-icon><ArrowDownBold /></el-icon>
              </el-button>
            </el-dropdown>
          </div>

          <!-- 其他操作按钮 -->
          <BaseButton type="primary" @click="action(currentRow, 'edit')">
            {{ t('action.edit') }}
          </BaseButton>
          <BaseButton type="danger" @click="returnPublic(currentRow)">
            {{ t('action.customer.returnPublic') }}
          </BaseButton>
          <BaseButton @click="back">
            {{ t('action.back') }}
          </BaseButton>
        </div>
      </div>
      <el-divider />
      <div class="nav flex flex-start items-center">
        <div class="div"
          ><text
            >负责人： {{ useEnumeratePicker(operatorOptions, currentRow?.owner ?? '') }}</text
          ></div
        >
        <div class="div"
          ><text>最后跟进时间： {{ currentRow?.last_followtime }}</text></div
        >
      </div>
      <br />
      <div>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="base_info" />
          <el-tab-pane label="全景图" name="panorama" />
          <el-tab-pane label="负责团队" name="team" />
          <el-tab-pane label="旅程" name="journey" />
          <el-tab-pane label="合同订单" name="contract_order" />
          <el-tab-pane label="工单记录" name="work_order_record" />
          <el-tab-pane label="回款管理" name="receipt_management" />
          <el-tab-pane label="开票历史" name="invoicing_history" />
          <el-tab-pane label="开票信息" name="invoicing_info" />
          <el-tab-pane label="退货退款" name="returns_refund" />
          <el-tab-pane label="文件柜" name="file_cabinet" />
          <el-tab-pane label="审批记录" name="approval_record" />
          <el-tab-pane label="抓取商品" name="marketplace" />
          <el-tab-pane label="跟进记录" name="follow_list" />
        </el-tabs>
        <!-- 动态加载对应的 tab 内容 -->
        <component
          :is="currentTabComponent"
          :current-row="currentRow"
          :operator-options="operatorOptions"
        />
      </div>
    </template>

    <!-- <div class="w-full flex justify-between">
      <Detail :current-row="currentRow" class="w-70%" />
      <TimeLine class="w-30%" :row="currentRow" />
    </div> -->
  </ContentDetailWrap>
</template>

<style lang="less" scoped>
:deep(.el-upload-list__item .el-icon--close:hover) {
  color: transparent !important;
  opacity: 0 !important;
  visibility: hidden;
}

:deep(.el-upload-list__item:hover .el-icon--close) {
  display: none;
}

:deep(.el-upload-list__item.is-success:focus:not(:hover)) {
  display: none !important;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px; /* 增加间距，使按钮不会挤在一起 */
}

.header-left .left {
  flex-direction: column;
  justify-content: space-around;
  margin-right: 10px;
}

.header-left .right .bottom span {
  margin-right: 10px;
}

.nav {
  gap: 50px;
}

.button-group {
  display: flex;
  align-items: center;
  gap: 0; /* 确保按钮组不额外增加间距 */
}

/* 主按钮样式 */
.main-button {
  margin-right: -1px; /* 让按钮无间隙连接 */
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

/* 下拉三角按钮 */
.triangle-button {
  display: flex;
  padding: 0 12px;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  align-items: center;
  justify-content: center;
}
</style>
